package com.ruoyi.project.mahjong.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.project.mahjong.domain.*;
import com.ruoyi.project.mahjong.domain.dto.RechargeDto;
import com.ruoyi.project.mahjong.domain.enu.CompareToStatus;
import com.ruoyi.project.mahjong.domain.enu.CostType;
import com.ruoyi.project.mahjong.domain.enu.MemberLogType;
import com.ruoyi.project.mahjong.domain.enu.ShopIncomeType;
import com.ruoyi.project.mahjong.domain.uyil.MemberLogUtil;
import com.ruoyi.project.mahjong.domain.vo.MemberCountVo;
import com.ruoyi.project.mahjong.domain.vo.MemberIntegralVo;
import com.ruoyi.project.mahjong.domain.vo.RechargeCompleteVo;
import com.ruoyi.project.mahjong.service.*;
import com.ruoyi.project.system.domain.SysDictData;
import com.ruoyi.project.system.service.ISysConfigService;
import com.ruoyi.project.system.service.ISysDictDataService;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.mahjong.mapper.TMemberMapper;
import org.springframework.transaction.annotation.Transactional;

/**
 * 会员管理Service业务层处理
 *
 * @author ruoyi
 * @date 2023-07-18
 */
@Service
public class TMemberServiceImpl implements ITMemberService {
    @Autowired
    private TMemberMapper tMemberMapper;
    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISysDictDataService dictDataService;

    @Autowired
    private ITablePoolService tablePoolService;
    @Autowired
    private ITIntegralService itIntegralService;
    @Autowired
    private ITRechargeMoneyService itRechargeMoneyService;
    @Autowired
    private ITMemberLogService tMemberLogService;
    @Autowired
    private ITRecordService recordService;
    @Autowired
    private RedisCache redisCache;


    /**
     * 查询会员管理
     *
     * @param id 会员管理ID
     * @return 会员管理
     */
    @Override
    public TMember selectTMemberById(Long id) {
        return tMemberMapper.selectTMemberById(id);
    }

    /**
     * 查询会员管理列表
     *
     * @param tMember 会员管理
     * @return 会员管理
     */
    @Override
    public List<TMember> selectTMemberList(TMember tMember) {
        List<TMember> tMembers = tMemberMapper.selectTMemberList(tMember);
//          SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        return tMembers;
    }

    /**
     * 新增会员管理
     *
     * @param tMember 会员管理
     * @return 结果
     */
    @Override
    public int insertTMember(TMember tMember) {
        tMember.setCreateTime(DateUtils.getNowDate());
        tMember.setMemberId("1");
        tMember.setMoney(new BigDecimal("0"));
        tMember.setSendMoney(new BigDecimal("0"));
        return tMemberMapper.insertTMember(tMember);
    }

    /**
     * 修改会员管理
     *
     * @param tMember 会员管理
     * @return 结果
     */
    @Override
    public int updateTMember(TMember tMember) {
        tMember.setUpdateTime(DateUtils.getNowDate());
//        String different = tMember.getDifferent();
//        StringBuilder sd=new StringBuilder();
//        String[] split = StringUtils.split(different, ",");
//        int i = split.length;
//        for (String s : split) {
//            i++;
//            if (split.length==i){
//                TMember tMember1 = tMemberMapper.selectTMemberById(Long.parseLong(s));
//                sd .append(tMember1.getName()) ;
//                break;
//            }
//            TMember tMember1 = tMemberMapper.selectTMemberById(Long.parseLong(s));
//            sd.append(tMember1.getName()+",") ;
//        }
//
//          tMember.setDifferent( sd.substring(0,1));
        return tMemberMapper.updateTMember(tMember);
    }

    /**
     * 批量删除会员管理
     *
     * @param ids 需要删除的会员管理ID
     * @return 结果
     */
    @Override
    public int deleteTMemberByIds(Long[] ids) {
        return tMemberMapper.deleteTMemberByIds(ids);
    }

    /**
     * 删除会员管理信息
     *
     * @param id 会员管理ID
     * @return 结果
     */
    @Override
    public int deleteTMemberById(Long id) {
        return tMemberMapper.deleteTMemberById(id);
    }

    @Override
    public List<String> getRecommend() {
        List<String> result = new ArrayList<>();
        String key = configService.selectConfigByKey(MyConstat.TIME_KEY);
        List<SysDictData> sysDictData = dictDataService.selectDictDataByType(MyConstat.TIME_DATE);
        Date date = DateUtils.getNowDate();
        for (SysDictData data : sysDictData) {
            String[] times = data.getDictLabel().split(":");
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(times[0]));//放入Date类型数据
            calendar.set(Calendar.MINUTE, Integer.parseInt(times[1]));                //时（24小时制）
            Date checkDate = calendar.getTime();
            long between = (checkDate.getTime() - date.getTime()) / 1000;//除以1000是为了转换成秒
            long hour = between % (24 * 3600) / 3600;
            if (hour <= Integer.parseInt(key) && hour >= 0) {
                result.add(data.getDictValue());
            }

        }
        return result;
    }

    @Override
    public List<TMember> recommend(TMember member, List<String> times) {
        StringBuilder builder = new StringBuilder();
        /* for(String s:times){
             builder.append(s+"|");
         }*/

        for (int i = 0; i < times.size(); i++) {
            String s = times.get(i);
            if (i != times.size() - 1) {
                builder.append(s + "|");
            } else {
                builder.append(s);
            }
        }
        if (builder.length() != 0) {
            builder.append("),");
            String reg = ",(" + builder.toString();
            List<TMember> result = tMemberMapper.recommend(member, reg);
           /* List<SysDictData> sysDictData = dictDataService.selectDictDataByType(MyConstat.TIME_DATE);
            for (TMember member1 : result) {
                StringBuffer buffer = new StringBuffer();
                if (ObjectUtil.isNotNull(member1.getPlayingTime())) {
                    String[] timeList = member1.getPlayingTime().split(",");
                    for (String s : timeList) {
                        for (SysDictData dictData : sysDictData) {
                            if (s.equals(dictData.getDictValue())) {
                                buffer.append(dictData.getDictLabel() + ",");
                            }
                        }
                    }
                }
                member1.setPlayingTime(buffer.toString());
            }*/
            return result;
        }

        return new ArrayList<>();

    }

    /**
     * 智能推荐到数据池
     */
    @Override
    public void goPollMember(TMember member) {
        TablePool pool = new TablePool();
        pool.setMemberId(member.getId());
        List<TablePool> tablePoolList = tablePoolService.selectTablePoolList(pool);
        if (ObjectUtil.isEmpty(tablePoolList)) {
            pool.setStatus(member.getStatus());
            pool.setState(member.getState());
            pool.setRemark(member.getRemark());
            pool.setMemberName(member.getName());
            try {
                tablePoolService.insertTablePool(pool);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public Integer updateTMemberById(Long id) {
        tMemberMapper.updateTMemberByid(id);
        return null;
    }

    @Override
    public Integer rollbackMember(Long id) {
        tMemberMapper.rollbackMember(id);
        return null;
    }

    @Override
    public List<TMember> selectTMemberByShopId(Long shopId) {
        return tMemberMapper.selectTMemberByShopId(shopId);

    }

    /**
     * 充值
     * 1 找到会员
     * 2 找到会员充值优惠表
     * 3 计算会员充值赠送金额
     * 5  增加店铺流水
     * RechargeCompleteVo=赠送了多少积分和点数
     * @return
     */
    @Override
    @Transactional
    public RechargeCompleteVo updateTMemberMoney(RechargeDto dto, Long shopId, Long staffId) {
//      最终返回结果
        RechargeCompleteVo vo = new RechargeCompleteVo();
//         增加店铺流水
        TRecord record = new TRecord();

        TMember tMember = tMemberMapper.selectTMemberById(dto.getMemberId());

        if(ObjectUtil.isNull(dto.getMoney())){
            dto.setMoney(new BigDecimal(0));
        }
        if(ObjectUtil.isNull(dto.getRechargeMoney())){
            dto.setRechargeMoney(new BigDecimal(0));
        }
        //处理赠送积分逻辑
        int giveIntegrals=  hanlerInteger(shopId,tMember,vo,dto);
        tMember.setMoney(tMember.getMoney().add(dto.getMoney()).add(dto.getRechargeMoney()));//添加总金额
        tMember.setStoredMoney(tMember.getStoredMoney().add(dto.getRechargeMoney()));//储值余额
        tMember.setSendMoney(tMember.getSendMoney().add(dto.getMoney()));//赠送金额

        //返回前端展示数据
        vo.setMoney(tMember.getMoney().toString());//赠送金额

        int i = tMemberMapper.updateTMember(tMember);
        if (i == 0) {
            throw new BaseException("充值失败,请重试");
        }
        Long jbid = redisCache.getCacheObject(shopId + staffId.toString());
        if(ObjectUtil.isNull(jbid)){
            throw new RuntimeException("该员工未上班，无法进行充值操作！");
        }
//     添加流水
        String orderNmuber = orderMethod();
        record.setShopId(Long.valueOf(tMember.getBelongShop()));
        record.setOrderNumber(orderNmuber);
        record.setStaffId(staffId);
        record.setHandoverId(jbid.toString());
        record.setShopId(shopId);
        record.setCostMemberId(tMember.getId());
        record.setCostMemberName(tMember.getName());
        record.setShopIncome(ShopIncomeType.INCOME.getValue());
        record.setIncomeType(dto.getPayType());
        record.setIncomeProjectType(CostType.RECHARGE.getValue());
        record.setMoney(Double.valueOf(dto.getRechargeMoney().toString()));
        record.setGiveMoney(Double.valueOf(dto.getMoney().toString()));
        record.setReceiveMoney(Double.valueOf(dto.getRechargeMoney().toString()));
        record.setRemark(dto.getRemark());
        Date date = new Date();
        record.setIncomeRefundTime(date);
        record.setReceiveIntegrai(String.valueOf(giveIntegrals));
        record.setCreateTime(date);
        record.setCreateBy(staffId.toString());
        recordService.insertTRecord(record);
//        添加日志
        TMemberLog tMemberLog = MemberLogUtil.insertMemberLog(
                shopId,
                staffId,
                tMember.getId(),
                String.valueOf(giveIntegrals),
                dto.getMoney(),
                null,
                dto.getRechargeMoney().toString(),
               MemberLogType.CZ.getValue() ,
                "充值:" + dto.getRechargeMoney() + ",赠送:" + dto.getMoney() + ",余额:" + tMember.getMoney(),
                dto.getRemark(),
                tMember.getMoney()
        );
        tMemberLogService.insertTMemberLog(tMemberLog);
        return vo;
    }

    private Integer hanlerInteger(Long shopId, TMember tMember,RechargeCompleteVo vo,RechargeDto dto) {

        TIntegral tIntegrals = itIntegralService.selectRechargeGiveintrgral(shopId);
        int giveIntegrals = 0;//赠送积分
        if (ObjectUtil.isNotNull(tIntegrals)) {
            //获取充值金额
            BigDecimal costMoeny=new BigDecimal(tIntegrals.getCostMoney());//获取充值金额
            if(costMoeny.intValue()!=0){
                int costNumber=dto.getRechargeMoney().divide(costMoeny,BigDecimal.ROUND_HALF_UP).intValue();//获取充值份数
                giveIntegrals=costNumber*tIntegrals.getIntegral().intValue();
            }


        }
        tMember.setIntegral(String.valueOf(Integer.valueOf(tMember.getIntegral()) + Integer.valueOf(giveIntegrals)));
        vo.setIntegral("赠送了" + giveIntegrals + "积分");
        tMember.setTotalIntegral(String.valueOf(Integer.valueOf(tMember.getTotalIntegral()) + Integer.valueOf(giveIntegrals)));
        return  giveIntegrals;

    }

    @Override
    public MemberCountVo selectMemberCountAndToDayAdd(Long shopId) {
        MemberCountVo vo = tMemberMapper.selectTMemCountberById(shopId);
        String s = tMemberMapper.selectToDayAdd(shopId);
        vo.setToday(s);
        Double saleMoney = tMemberMapper.sendMoney(shopId);
        if(ObjectUtils.isNull(saleMoney)){
            vo.setSaleMoney(new BigDecimal(0));
        }else{
            vo.setSaleMoney(new BigDecimal(saleMoney));
        }
        Double storedMoney = tMemberMapper.storedMoney(shopId);
        if(ObjectUtils.isNull(storedMoney)){
            vo.setStoredMoney(new BigDecimal(0));
        }else{
            vo.setStoredMoney(new BigDecimal(storedMoney));
        }
        return vo;
    }

    @Override
    public Integer updateTMemberRefund(TMember tMember, Long userId, Long shopId,String remark) {
        Integer integer = tMemberMapper.updateTMemberRefund(tMember);
        if (integer == 0) {
            throw new BaseException("会员余额小于退款金额");
        }
//        String s = orderMethod();
        //添加日志
        TMember member = tMemberMapper.selectTMemberById(tMember.getId());
        TMemberLog tMemberLog = MemberLogUtil.insertMemberLog(
                Long.valueOf(tMember.getBelongShop()),
                userId,
                tMember.getId(),
                null,
                null,
                null,
                tMember.getMoney().toString(),
                MemberLogType.QK.getValue(),
                "退款:"+tMember.getMoney() + ",余额:" + member.getMoney(),
                "null".equals(remark)?null:remark,
                member.getMoney()
        );
        int i1 = tMemberLogService.insertTMemberLog(tMemberLog);
        Long jbid = redisCache.getCacheObject(shopId + userId.toString());
         if(null==jbid){
             throw  new RuntimeException("该人员未上班");
         }
        TRecord record = new TRecord();

        record.setOrderNumber(orderMethod());
        record.setStaffId(userId);
        record.setHandoverId(jbid.toString());
        record.setCostMemberId(tMember.getId());
        record.setShopId(Long.valueOf(tMember.getBelongShop()));
        record.setShopIncome(ShopIncomeType.PAYMENT.getValue());
        record.setIncomeProjectType("-3");
        record.setIsRefund("1");
        record.setRefundMoney(Double.valueOf(tMember.getMoney().toString()));
        record.setIncomeRefundTime(new Date());
        record.setCreateTime(new Date());
        record.setCreateBy(userId.toString());
        record.setRemark(remark);
        int i = recordService.insertTRecord(record);
        if (integer == 0 || i1 == 0 || i == 0) {
            throw new BaseException("退款失败,请重试");
        }
        return integer;
    }

    @Override
    public List<MemberIntegralVo> selectMemberIntegral(Long shopId, Long id, String startTime, String endTime) {
        List<MemberIntegralVo> voList = tMemberMapper.selectMemberIntegral(shopId, id, startTime, endTime);
        for (MemberIntegralVo vo : voList) {
            if (vo.getSource().equals("-1")) {
                vo.setSourceName("商品消费");
            } else if (vo.getSource().equals("-2")) {
                vo.setSourceName("会员充值");
            } else {
                vo.setSourceName("桌台消费");
            }
        }
        return voList;
    }

    @Override
    public Integer updateTMemberProductCostMoney(BigDecimal costMoney, Long memberId, int intergral) {
        return tMemberMapper.updateTMemberProductCostMoney(costMoney, memberId, intergral);
    }

    @Override
    public List<TMember> selectMemberByLikeName(String name, Long shopId) {
        return tMemberMapper.selectMemberByLikeName(name, shopId);
    }

    @Override
    public Integer updateGiveMoney(String money, String id) {
        return tMemberMapper.updateGiveMoney(money, id);
    }



    @Override
    public Integer updateTMemberSendMoney(Long  memberId,BigDecimal money, Long userId, Long shopId, String remark) {
        //更新会员余额信息
        TMember member=selectTMemberById(memberId);
        if(null==member.getSendMoney()){
            member.setSendMoney(new BigDecimal(0));
        }
        member.setSendMoney(member.getSendMoney().add(money));
        member.setMoney(member.getMoney().add(money));
        int result= updateTMember(member);

       TMemberLog tMemberLog = MemberLogUtil.insertMemberLog(
                shopId,
                userId,
                memberId,
                null,
                null,
                money,
                null,
                MemberLogType.ZS.getValue(),
                "赠送金额:"+money + ",余额:" + member.getMoney(),
                remark,
                member.getMoney()
        );
        tMemberLogService.insertTMemberLog(tMemberLog);
        return result;
    }

    /**
     * 结账操作
     * @param memberId
     * @param deskId
     */
    @Override
    public void checkout(Long memberId, Long deskId) {





    }

    /**
     * 订单id生成
     *
     * @return
     */
    public String orderMethod() {
        Random random = new Random();
        int i = random.nextInt(9000) + 1000;
        return String.valueOf(System.currentTimeMillis() + i);
    }
}
//         最优充值赠送积分方案
//        String rechargeMoney =null;//最合适的充值方案金额
//         List<Integer> where=new ArrayList<>();
//        for (TIntegral tIntegral : tIntegrals) {
//            where.add(Integer.valueOf(tIntegral.getRechargeMoney()));
//        }
//        where = where.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
//        for (int i = 0; i < where.size(); i++) {
//             int i1 = moneys.compareTo(new BigDecimal(where.get(i)));
//            if (i1!=-1){
//                rechargeMoney=where.get(i).toString();
//                break;
//            }
//        }
//Long finaLtIntegral=0l;//最终赠送积分
//      if (rechargeMoney!=null) {
//              for (TIntegral tIntegral : tIntegrals) {
//              boolean equals = tIntegral.getRechargeMoney().equals(rechargeMoney);
//              if (equals) {//满足充值赠送积分状态
//              finaLtIntegral =  tIntegral.getIntegral();
//              break;
//              }
//              }
//              vo.setIntegral("赠送了" + finaLtIntegral + "积分");
//              record.setReceiveIntegrai(finaLtIntegral.toString());
//              tMember.setIntegral(String.valueOf(Long.valueOf(tMember.getIntegral()) + finaLtIntegral));
//              }
